<template>
	<div class="container flex justify-center items-center">
		<a-form
			ref="formRef"
			name="loginForm"
			class="login-form border rounded-md border-solid px-10 pt-5 shadow-lg bg-gray-300"
			v-bind="layout"
			:model="formState"
			@finish="onSubmit"
			labelAlign="left"
		>
			<div class="font-medium text-2xl py-4 text-center">Please Login</div>
			<div class="text-sm text-red-500 py-2 text-center italic" v-if="!hasInitData">
				Before using, please click Init Button first
			</div>
			<a-form-item
				label="Username"
				name="account"
				:rules="[{ required: true, message: 'Please input your username!' }]"
			>
				<a-input v-model:value="formState.account" placeholder="admin or guest">
					<template #prefix>
						<UserOutlined class="site-form-item-icon" />
					</template>
				</a-input>
			</a-form-item>
			<a-form-item
				label="Password"
				name="password"
				:rules="[{ required: true, message: 'Please input your password!' }]"
				class="text-justify"
			>
				<a-input-password v-model:value="formState.password" placeholder="admin or guest">
					<template #prefix>
						<LockOutlined class="site-form-item-icon" />
					</template>
				</a-input-password>
			</a-form-item>

			<a-form-item
				:wrapperCol="{ span: !hasInitData ? 16 : 24, offset: hasInitData ? 8 : 0 }"
				class="form-submit"
			>
				<div class="flex justify-around">
					<a-button type="primary" @click="initData" v-if="!hasInitData"> Init </a-button>
					<a-button :disabled="disabled" type="primary" class="grow" html-type="submit">
						Login
					</a-button>
				</div>
			</a-form-item>
		</a-form>
	</div>
</template>

<script setup lang="ts">
import { hadInitData, init, login } from '@/apis/account';
import type { LoginFormState } from '@/types/account';
import { STORAGE_TOKEN_KEY } from '@/types/meta/constants';
import { FormInstance, message } from 'ant-design-vue';
import { useRequest } from 'vue-hooks-plus';
const formRef = ref<FormInstance>();
const layout = {
	labelCol: { span: 8 },
	wrapperCol: { span: 16 },
};
const formState = reactive<LoginFormState>({
	account: '',
	password: '',
});
const hasInitData = ref<boolean>(false);

const router = useRouter();

const initData = () => {
	init().then((res) => {
		if (res) {
			message.success('Init Data Successfully');
			hasInitData.value = true;
		}
	});
};

useRequest(hadInitData, {
	onSuccess: (data: boolean) => {
		hasInitData.value = data;
	},
});

const disabled = computed(() => {
	return !(formState.account && formState.password);
});

const onSubmit = (values: LoginFormState) => {
	login(values).then((value) => {
		if (value) {
			localStorage.setItem(STORAGE_TOKEN_KEY, value);
			router.push({
				name: 'root',
			});
		}
	});
};
</script>

<style lang="less"></style>
